package com.xywy.beautyand.vollery;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.xywy.beautyand.util.LogUtil;

public class BaseRequest<T> extends Request<T> {
	protected Gson mGson;
	protected Class<T> mClazz;
	protected OnVolleyResponseListener<T> onResponseListener;
	protected boolean isParseJson = true;

	public BaseRequest(int method, String url, Class<T> mClazz,
			OnVolleyResponseListener<T> onVolleyResponseListener) {
		super(method, url, null);
		LogUtil.d(this, "url: " + url);
		if (mGson == null)
			mGson = new Gson();
		this.mClazz = mClazz;
		this.onResponseListener = onVolleyResponseListener;
	}

	public void setIsParseJson(boolean isParseJson) {
		this.isParseJson = isParseJson;
	}

	/**
	 */
	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		Map<String, String> headers = new HashMap<String, String>();
		// headers.put("mysessionid", "");
		return headers;
	}

	@Override
	protected void deliverResponse(T response) {
		onResponseListener.onSuccess(response);
	}

	@Override
	public void deliverError(VolleyError error) {
		super.deliverError(error);
		LogUtil.e(this, error.getLocalizedMessage());
		onResponseListener.onError(error);
	}

	@Override
	protected Response<T> parseNetworkResponse(NetworkResponse response) {
		LogUtil.i("请求返回...", response + "");
		try {
			String json = new String(response.data,
					HttpHeaderParser.parseCharset(response.headers));
			try {
				JSONObject jsonObject = new JSONObject(json);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			System.out.println("json  ::-- " + json);
			// LogUtil.i_urldecode(this, json);

			if (isParseJson) {
				return Response.success(mGson.fromJson(json, mClazz),
						HttpHeaderParser.parseCacheHeaders(response));
			} else {
				return Response.success((T) json,
						HttpHeaderParser.parseCacheHeaders(response));
			}
		} catch (UnsupportedEncodingException e) {
			return Response.error(new ParseError(e));
		} catch (JsonSyntaxException e) {
			return Response.error(new ParseError(e));
		}
	}
}
